/*
 * Ext JS Library 2.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

FeedGrid = function(viewer, config) {

	this.myRecordObj = Ext.data.Record.create([
		/**
		 * Note the order of the fields defined here does not matter. The order
		 * specified here does not relate to the order of the fields in your
		 * source, nor the order displayed in the grid. You also do not have to
		 * include every field that is in your data source here either.  So, if
		 * your database table has 10 columns, you can specify 2 here if you
		 * want 
	     * name:    The 'name' by which the field is referenced within
	     *          the Record. Whatever is specified here should match
	     *          the columnModel "dataIndex" property
	     * mapping: Mapping is only required if the 'reference' does
	     *          not equal the mapping, where 'reference' is the key
	     *          in the source data file, eg. db field name, xml
	     *          tag name, etc.
	     * sortDir: initial sort direction
	     * sortType: defines explicitly how to perform the sort, see
	     *           Ext.data.SortTypes
	     * type:    How the data should be displayed
	       *          When type='date' make sure to specify a dateFormat that
	       *          matches what is coming from the data source (see 'Class
	       *          Date' in API)
		 * Example from XML data:
		 * - <Item>
		 *       <ASIN>0446355453</ASIN> 
		 *       <DetailPageURL>http://www.amazon.com/something</DetailPageURL>
		 *     - <ItemAttributes>
		 *           <Author>Sidney Sheldon</Author> 
		 *           <Manufacturer>Warner Books</Manufacturer>
		 *           <ProductGroup>Book</ProductGroup>
		 *           <Title>Master of the Game</Title>
		 *       </ItemAttributes>
		 *   </Item>
		 *
		 *	{name:'Author', mapping: 'ItemAttributes > Author'},//example of nested reference 
		 * 	{name:'Title'}, 
		 *	{name:'Manufacturer'}, 
		 *	{name:'ProductGroup'}
		 */
	          {name: 'fabricante'},
	          {name: 'modelo'},
	          {name: 'urlFab'},
	          {name: 'descricao'},
	          {name: 'urlDetalheFab'},
	          {name: 'garantia'},
	          {name: 'preco', type: 'float'},
	          {name: 'anunciante'},
	          {name: 'telefone'},
	          {name: 'cidade'},
	          {name: 'bairro'},
	          {name: 'uf'},
	          {name: 'dataPub', type: 'date', dateFormat: 'Y-m-d H:i:s'}
	]);

	this.viewer = viewer;
    Ext.apply(this, config);
    //carrega o grid de produtos
    this.store = new Ext.data.JsonStore({
        proxy: new Ext.data.HttpProxy({
            url: 'json/data/get-gridProdutos.php',
            method: 'POST'
        }),
        reader: this.myRecordObj
    });
    this.store.setDefaultSort('preco', "DESC");

    this.columns = [{
        id: 'fabricante',
        header: "Fabricante",
        dataIndex: 'fabricante',
        sortable:true,
        width: 120,
        renderer: this.formatTitle
      },{
        header: "Modelo",
        dataIndex: 'modelo',
        width: 100,
        sortable:true
      },{
          id: 'preco',
          header: "Valor",
          dataIndex: 'preco',
          width: 150,
          sortable:true
      },{
          id: 'anunciante',
          header: "Anunciante",
          dataIndex: 'anunciante',
          width: 150,
          sortable:true
      },{
        id: 'telefone',
        header: "Telefone",
        dataIndex: 'telefone',
        width: 150,
        sortable:true
    },{
        id: 'cidade',
        header: "Cidade",
        dataIndex: 'cidade',
        width: 150,
        sortable:true
    }];

    FeedGrid.superclass.constructor.call(this, {
        region: 'center',
        id: 'topic-grid',
        loadMask: {msg:'Loadiiiiing Feed...'},

        sm: new Ext.grid.RowSelectionModel({
            singleSelect:true
        }),

        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            showPreview:true,
            getRowClass : this.applyRowClass
        }
    });

    this.on('rowcontextmenu', this.onContextClick, this);
};

Ext.extend(FeedGrid, Ext.grid.GridPanel, {

    onContextClick : function(grid, index, e){
        if(!this.menu){ // create context menu on first right click
            this.menu = new Ext.menu.Menu({
                id:'grid-ctx',
                items: [{
                    text: 'View in new tab',
                    iconCls: 'new-tab',
                    scope:this,
                    handler: function(){
                        this.viewer.openTab(this.ctxRecord);
                    }
                },{
                    iconCls: 'new-win',
                    text: 'Go to Post',
                    scope:this,
                    handler: function(){
                        window.open(this.ctxRecord.data.link);
                    }
                },'-',{
                    iconCls: 'refresh-icon',
                    text:'Refresh',
                    scope:this,
                    handler: function(){
                        this.ctxRow = null;
                        this.store.reload();
                    }
                }]
            });
            this.menu.on('hide', this.onContextHide, this);
        }
        e.stopEvent();
        if(this.ctxRow){
            Ext.fly(this.ctxRow).removeClass('x-node-ctx');
            this.ctxRow = null;
        }
        this.ctxRow = this.view.getRow(index);
        this.ctxRecord = this.store.getAt(index);
        Ext.fly(this.ctxRow).addClass('x-node-ctx');
        this.menu.showAt(e.getXY());
    },

    onContextHide : function(){
        if(this.ctxRow){
            Ext.fly(this.ctxRow).removeClass('x-node-ctx');
            this.ctxRow = null;
        }
    },

    loadFeed : function(url) {
        this.store.baseParams = {
            feed: url
        };
        this.store.load();
    },

    togglePreview : function(show){
        this.view.showPreview = show;
        this.view.refresh();
    },

    // within this function "this" is actually the GridView
    applyRowClass: function(record, rowIndex, p, ds) {
        if (this.showPreview) {
            var xf = Ext.util.Format;
            p.body = '<p>' + xf.ellipsis(xf.stripTags(record.data.description), 200) + '</p>';
            return 'x-grid3-row-expanded';
        }
        return 'x-grid3-row-collapsed';
    },

    formatDate : function(date) {
        if (!date) {
            return '';
        }
        var now = new Date();
        var d = now.clearTime(true);
        var notime = date.clearTime(true).getTime();
        if (notime == d.getTime()) {
            return 'Today ' + date.dateFormat('g:i a');
        }
        d = d.add('d', -6);
        if (d.getTime() <= notime) {
            return date.dateFormat('D g:i a');
        }
        return date.dateFormat('n/j g:i a');
    },

    formatTitle: function(value, p, record) {
        return String.format(
                '<div class="topic"><b>{0}</b><span class="author">{1}</span></div>',
                value, record.data.modelo, record.id, record.data.fabricante
                );
    }
});